package com.serie402.business.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.kiss.fw.dto.AbstractDAODTO;
import com.kiss.fw.exceptions.DAOException;
import com.kiss.fw.utils.Constants;
import com.kiss.fw.utils.Util;
import com.serie402.business.dao.dto.EventDAODTO;
import com.serie402.business.dao.mappers.EventMapper;
import com.serie402.common.bo.Event;

public final class EventsDAO extends Serie402DAO {
	private static final Logger logger = Logger.getLogger(EventsDAO.class);
	private static final EventsDAO instance = new EventsDAO();
	
	private EventsDAO() {
	}
	
	private EventDAODTO getEventDAODTO(final AbstractDAODTO _dto) {
		return (EventDAODTO)_dto;
	}
	
	public static EventsDAO getInstance() {
		return instance;
	}
	
	@Override
	public AbstractDAODTO create(AbstractDAODTO _dto) throws DAOException {
		return _dto;
	}
	
	@Override
	public AbstractDAODTO read(AbstractDAODTO _dto) throws DAOException {
		EventDAODTO dto = getEventDAODTO(_dto);
		
		SqlSession sqlSession = openSqlSession();
		
		if(sqlSession != null) {
			List<Event> events;
			EventMapper eventMapper = MapperFactory.getEventMapper(sqlSession);
			
			if(dto.getEventId() > 0) {
				Event event;
				
				try {
					event = eventMapper.retrieveEvent(dto.getEventId());
				}
				catch(Exception _exception) {
					Util.handleException(logger, "EventMapper.retrieveEvent(_eventId) - Error", _exception);
					throw Constants.Exceptions.STORED_PROCEDURE_EXCEPTION;
				}
				
				if(event != null) {
					events = new ArrayList<Event>(1);
					events.add(event);
				}
			}
			else {
				try {
					// load events
					events = eventMapper.retrieveEvents();
				}
				catch(Exception _exception) {
					Util.handleException(logger, "EventMapper.retrieveEvents() - Error", _exception);
					throw Constants.Exceptions.STORED_PROCEDURE_EXCEPTION;
				}
				
				if(events != null && events.size() > 0) {
					dto.setEvents(events);
				}
			}
		}
		
		return dto;
	}
	
	@Override
	public AbstractDAODTO update(AbstractDAODTO _dto) throws DAOException {
		return _dto;
	}
	
	@Override
	public AbstractDAODTO delete(AbstractDAODTO _dto) throws DAOException {
		return _dto;
	}

	@Override
	public AbstractDAODTO search(AbstractDAODTO _dto) throws DAOException {
		return _dto;
	}
}